Code
This kernel has been released under the Apache 2.0 open source license.
Download Code{
"cells": [
{
"metadata": {
"_uuid": "fff77fab01808778146d3238f47a3efd03b9913a"
},
"cell_type": "markdown",
"source": "# Convolutional Neural Networks\n\n## Project: Write an Algorithm for a Dog Identification App \n\n---\n\nIn this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'(IMPLEMENTATION)'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully! \n\n> **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to **File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.\n\nIn addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.\n\n>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.\n\nThe rubric contains _optional_ \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. If you decide to pursue the \"Stand Out Suggestions\", you should include the code in this Jupyter notebook.\n\n\n\n---\n### Why We're Here \n\nIn this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!). \n\n\n\nIn this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!\n\n### The Road Ahead\n\nWe break the notebook into separate steps. Feel free to use the links below to navigate the notebook.\n\n* [Step 0](#step0): Import Datasets\n* [Step 1](#step1): Detect Humans\n* [Step 2](#step2): Detect Dogs\n* [Step 3](#step3): Create a CNN to Classify Dog Breeds (from Scratch)\n* [Step 4](#step4): Create a CNN to Classify Dog Breeds (using Transfer Learning)\n* [Step 5](#step5): Write your Algorithm\n* [Step 6](#step6): Test Your Algorithm\n\n---\n<a id='step0'></a>\n## Step 0: Import Datasets\n\nMake sure that you've downloaded the required human and dog datasets:\n* Download the [dog dataset](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/dogImages.zip). Unzip the folder and place it in this project's home directory, at the location `/dogImages`. \n\n* Download the [human dataset](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/lfw.zip). Unzip the folder and place it in the home diretcory, at location `/lfw`. \n\n*Note: If you are using a Windows machine, you are encouraged to use [7zip](http://www.7-zip.org/) to extract the folder.*\n\nIn the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays `human_files` and `dog_files`."
},
{
"metadata": {
"trusted": true,
"_uuid": "edebd5bed828b8a64cb3c8445b323ff4c85ac89e"
},
"cell_type": "code",
"source": "import os\nos.listdir('../input/')",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "bb2041cb46a5556786e0f3ee7bf3b08aa9d8a5b6"
},
"cell_type": "code",
"source": "import numpy as np\nfrom glob import glob\n\n# load filenames for human and dog images\nhuman_files = np.array(glob(\"../input/dogclassification/lfw/lfw/*/*\"))\ndog_files = np.array(glob(\"../input/dogclassification/dogimages/dogImages/*/*/*\"))\n\n# print number of images in each dataset\nprint('There are %d total human images.' % len(human_files))\nprint('There are %d total dog images.' % len(dog_files))",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "81dba9afd26d72f93fa9cff4267759b7112be341"
},
"cell_type": "markdown",
"source": "<a id='step1'></a>\n## Step 1: Detect Humans\n\nIn this section, we use OpenCV's implementation of [Haar feature-based cascade classifiers](http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html) to detect human faces in images. \n\nOpenCV provides many pre-trained face detectors, stored as XML files on [github](https://github.com/opencv/opencv/tree/master/data/haarcascades). We have downloaded one of these detectors and stored it in the `haarcascades` directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image."
},
{
"metadata": {
"trusted": true,
"_uuid": "282cfc68f533baaadd98f7e892eeb4ca1ffb4f19"
},
"cell_type": "code",
"source": "import cv2 \nimport matplotlib.pyplot as plt \n%matplotlib inline \n\n# extract pre-trained face detector\nface_cascade = cv2.CascadeClassifier('../input/haarcascades/haarcascade_frontalface_alt.xml')\n\n# load color (BGR) image\nimg = cv2.imread(human_files[0])\n# convert BGR image to grayscale\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# find faces in image\nfaces = face_cascade.detectMultiScale(gray)\n\n# print number of faces detected in the image\nprint('Number of faces detected:', len(faces))\n\n# get bounding box for each detected face\nfor (x,y,w,h) in faces:\n # add bounding box to color image\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n \n# convert BGR image to RGB for plotting\ncv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n# display the image, along with bounding box\nplt.imshow(cv_rgb)\nplt.show()",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "d79901741858373b8fc441be2e02267615e950b7"
},
"cell_type": "markdown",
"source": "Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The `detectMultiScale` function executes the classifier stored in `face_cascade` and takes the grayscale image as a parameter. \n\nIn the above code, `faces` is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as `x` and `y`) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as `w` and `h`) specify the width and height of the box.\n\n### Write a Human Face Detector\n\nWe can use this procedure to write a function that returns `True` if a human face is detected in an image and `False` otherwise. This function, aptly named `face_detector`, takes a string-valued file path to an image as input and appears in the code block below."
},
{
"metadata": {
"trusted": true,
"_uuid": "7455b28a169777f5dfd8589b596169c5abc7da32"
},
"cell_type": "code",
"source": "# returns \"True\" if face is detected in image stored at img_path\ndef face_detector(img_path):\n img = cv2.imread(img_path)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray)\n return len(faces) > 0",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "625a38c0e74bed26b79f35878be60c6be0da5ab3"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Assess the Human Face Detector\n\n__Question 1:__ Use the code cell below to test the performance of the `face_detector` function. \n- What percentage of the first 100 images in `human_files` have a detected human face? \n- What percentage of the first 100 images in `dog_files` have a detected human face? \n\nIdeally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays `human_files_short` and `dog_files_short`."
},
{
"metadata": {
"_uuid": "f35cdfa1205bd7f1c226d107681fbcccd9f6312c"
},
"cell_type": "markdown",
"source": "__Answer:__ \n(You can print out your results and/or write your percentages in this cell)"
},
{
"metadata": {
"trusted": true,
"_uuid": "99e8d8bff678b9f476f4f05e64f4e668f1b51632"
},
"cell_type": "code",
"source": "from tqdm import tqdm\n\nhuman_files_short = human_files[:100]\ndog_files_short = dog_files[:100]\n\n#-#-# Do NOT modify the code above this line. #-#-#\n\n## TODO: Test the performance of the face_detector algorithm \n## on the images in human_files_short and dog_files_short.\ndef detect_human(files):\n count = 0\n total_count = len(files)\n for file in files:\n if face_detector(file):\n count+=1\n return (count,total_count)",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "bd10728d16b00d5f53946df7ae77a5b738b6c9de"
},
"cell_type": "code",
"source": "print(\"Human in Human Files is {} / {}\".format(detect_human(human_files_short)[0],detect_human(human_files_short)[1]))\nprint(\"Human in Dog Files is {} / {}\".format(detect_human(dog_files_short)[0],detect_human(dog_files_short)[1]))",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "81a305f9844c396e40cd955a95ba18cb3311bd69"
},
"cell_type": "markdown",
"source": "We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this _optional_ task, report performance on `human_files_short` and `dog_files_short`."
},
{
"metadata": {
"trusted": true,
"_uuid": "d31556b1b46bf431b0191831ccf3c74fc6f73d36"
},
"cell_type": "code",
"source": "### (Optional) \n### TODO: Test performance of anotherface detection algorithm.\n### Feel free to use as many code cells as needed.",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "2ba8cec29ab03a21d2a37842a6f391b60880d82d"
},
"cell_type": "markdown",
"source": "---\n<a id='step2'></a>\n## Step 2: Detect Dogs\n\nIn this section, we use a [pre-trained model](http://pytorch.org/docs/master/torchvision/models.html) to detect dogs in images. \n\n### Obtain Pre-trained VGG-16 Model\n\nThe code cell below downloads the VGG-16 model, along with weights that have been trained on [ImageNet](http://www.image-net.org/), a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of [1000 categories](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a). "
},
{
"metadata": {
"trusted": true,
"_uuid": "64df0ea2832643058649b36203e10da6a502d002"
},
"cell_type": "code",
"source": "import torch\nimport torchvision.models as models\n\n# define VGG16 model\nVGG16 = models.vgg16(pretrained=True)\n\n# check if CUDA is available\nuse_cuda = torch.cuda.is_available()\n\n# move model to GPU if CUDA is available\nif use_cuda:\n VGG16 = VGG16.cuda()",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "8bdd0430bf0b46afcf32b693958ada03b6b12ff0"
},
"cell_type": "markdown",
"source": "\nGiven an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image."
},
{
"metadata": {
"_uuid": "cae6ca3dccbe8e081b29d1b8d73486d7f0a44c74"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Making Predictions with a Pre-trained Model\n\nIn the next code cell, you will write a function that accepts a path to an image (such as `'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg'`) as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.\n\nBefore writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the [PyTorch documentation](http://pytorch.org/docs/stable/torchvision/models.html)."
},
{
"metadata": {
"trusted": true,
"_uuid": "e9df12aa0f835a93c83fde4adedda9fdef35a210"
},
"cell_type": "code",
"source": "from PIL import Image\nimport torchvision.transforms as transforms\n\ndef load_image(img_path):\n image = Image.open(img_path).convert('RGB')\n # resize to (244,244) because VGG16 accepts that dimension\n in_transform = transforms.Compose([\n transforms.Resize(size=(244,244)),\n transforms.ToTensor()]) #Normalization parameter from PyTorch Doc\n # discard the transparent, alpha channel (that's the :3) and add the batch dimension\n image = in_transform(image)[:3,:,:].unsqueeze(0)\n return image",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "6ba9b2d795f6fd249007bec7be2688339d92f23b"
},
"cell_type": "code",
"source": "def VGG16_predict(img_path):\n '''\n Use pre-trained VGG-16 model to obtain index corresponding to \n predicted ImageNet class for image at specified path\n \n Args:\n img_path: path to an image\n \n Returns:\n Index corresponding to VGG-16 model's prediction\n '''\n ## TODO: Complete the function.\n ## Load and pre-process an image from the given img_path\n ## Return the *index* of the predicted class for that image\n img = load_image(img_path)\n if use_cuda:\n img = img.cuda()\n ret = VGG16(img)\n return torch.max(ret,1)[1].item() # predicted class index\n",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "8ab86e412dc773701582d688542dad594d4d2e0f"
},
"cell_type": "code",
"source": "VGG16_predict(dog_files[0])",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "6bef39214413b1c05779f7622c74a82f1578f14b"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Write a Dog Detector\n\nWhile looking at the [dictionary](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a), you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from `'Chihuahua'` to `'Mexican hairless'`. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).\n\nUse these ideas to complete the `dog_detector` function below, which returns `True` if a dog is detected in an image (and `False` if not)."
},
{
"metadata": {
"trusted": true,
"_uuid": "1df7cc5850ef6f364c4b01a3947268595d56fa10"
},
"cell_type": "code",
"source": "### returns \"True\" if a dog is detected in the image stored at img_path\ndef dog_detector(img_path):\n ## TODO: Complete the function.\n chk = VGG16_predict(img_path)\n if chk >=151 and chk<=268:\n return True\n return False # true/false",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "e6bf0194d17fb47bc3dbc6a0b59f317217f1dbc2"
},
"cell_type": "code",
"source": "print(dog_detector(dog_files_short[0]))\nprint(dog_detector(human_files_short[0]))",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "eed8261458e80ddfb9cefbbe10d2d2d7542b9756"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Assess the Dog Detector\n\n__Question 2:__ Use the code cell below to test the performance of your `dog_detector` function. \n- What percentage of the images in `human_files_short` have a detected dog? \n- What percentage of the images in `dog_files_short` have a detected dog?"
},
{
"metadata": {
"_uuid": "3e141c460071b244854583d0373f4ab882def5f1"
},
"cell_type": "markdown",
"source": "__Answer:__ \n"
},
{
"metadata": {
"trusted": true,
"_uuid": "7bc60f95847669562fda553353a679031e8b26bd"
},
"cell_type": "code",
"source": "### TODO: Test the performance of the dog_detector function\n### on the images in human_files_short and dog_files_short.\ndef dog_detect(files):\n detect_count = 0\n total_count = len(files)\n for dog in files:\n if dog_detector(dog):\n detect_count += 1\n return (detect_count, total_count)",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "1d633815638f7215f3654f950cfd22add78805fb"
},
"cell_type": "code",
"source": "print(\"Dogs in Human Files : {} / {}\".format(dog_detect(human_files_short)[0],len(human_files_short)))\nprint(\"Dogs in Dog Files : {} / {}\".format(dog_detect(dog_files_short)[0],len(dog_files_short)))",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "eba032b1a5a751298fc7ac7b07c403b374b64edb"
},
"cell_type": "markdown",
"source": "We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as [Inception-v3](http://pytorch.org/docs/master/torchvision/models.html#inception-v3), [ResNet-50](http://pytorch.org/docs/master/torchvision/models.html#id3), etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this _optional_ task, report performance on `human_files_short` and `dog_files_short`."
},
{
"metadata": {
"trusted": true,
"_uuid": "5a4249175c73615c92c5f8799a269ec5c8535318"
},
"cell_type": "code",
"source": "### (Optional) \n### TODO: Report the performance of another pre-trained network.\n### Feel free to use as many code cells as needed.",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "a5e00f1f64425c493c7ee80aa7cc81c4e8735ddb"
},
"cell_type": "markdown",
"source": "---\n<a id='step3'></a>\n## Step 3: Create a CNN to Classify Dog Breeds (from Scratch)\n\nNow that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN _from scratch_ (so, you can't use transfer learning _yet_!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.\n\nWe mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that *even a human* would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel. \n\nBrittany | Welsh Springer Spaniel\n- | - \n<img src=\"images/Brittany_02625.jpg\" width=\"100\"> | <img src=\"images/Welsh_springer_spaniel_08203.jpg\" width=\"200\">\n\nIt is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels). \n\nCurly-Coated Retriever | American Water Spaniel\n- | -\n<img src=\"images/Curly-coated_retriever_03896.jpg\" width=\"200\"> | <img src=\"images/American_water_spaniel_00648.jpg\" width=\"200\">\n\n\nLikewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed. \n\nYellow Labrador | Chocolate Labrador | Black Labrador\n- | -\n<img src=\"images/Labrador_retriever_06457.jpg\" width=\"150\"> | <img src=\"images/Labrador_retriever_06455.jpg\" width=\"240\"> | <img src=\"images/Labrador_retriever_06449.jpg\" width=\"220\">\n\nWe also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%. \n\nRemember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!\n\n### (IMPLEMENTATION) Specify Data Loaders for the Dog Dataset\n\nUse the code cell below to write three separate [data loaders](http://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) for the training, validation, and test datasets of dog images (located at `dogImages/train`, `dogImages/valid`, and `dogImages/test`, respectively). You may find [this documentation on custom datasets](http://pytorch.org/docs/stable/torchvision/datasets.html) to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of [transforms](http://pytorch.org/docs/stable/torchvision/transforms.html?highlight=transform)!"
},
{
"metadata": {
"trusted": true,
"_uuid": "9f7a5db6a3c5bd8018f5df43c79fe682780784eb"
},
"cell_type": "code",
"source": "import os\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\n\n### TODO: Write data loaders for training, validation, and test sets\n## Specify appropriate transforms, and batch_sizes\n\nbatch_size = 20\nnum_workers = 0\ntrain_dir = \"../input/dogclassification/dogimages/dogImages/train\"\nvalid_dir = \"../input/dogclassification/dogimages/dogImages/valid\"\ntest_dir = \"../input/dogclassification/dogimages/dogImages/test\"\n\n\n\nstandard_normalization = transforms.Normalize(mean=[0.485,0.456,0.406],\n std=[0.299,0.244,0.255])\n",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "0c60b18a7da73a16091405fd8db280aebe57d274"
},
"cell_type": "code",
"source": "data_transforms = {'train': transforms.Compose([transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n standard_normalization]),\n 'val': transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n standard_normalization]),\n 'test': transforms.Compose([transforms.Resize(size=(224,224)),\n transforms.ToTensor(), \n standard_normalization])\n }",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "29fca11ef9cca6cba8f5771164c0546f0ae9be9a"
},
"cell_type": "code",
"source": "train_data = datasets.ImageFolder(train_dir, transform=data_transforms['train'])\nvalid_data = datasets.ImageFolder(valid_dir, transform=data_transforms['val'])\ntest_data = datasets.ImageFolder(test_dir, transform=data_transforms['test'])",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "51de7484ffe09bdd5f7095bd51743bdf40550d3b"
},
"cell_type": "code",
"source": "train_loader = torch.utils.data.DataLoader(train_data,\n batch_size=batch_size, \n num_workers=num_workers,\n shuffle=True)\nvalid_loader = torch.utils.data.DataLoader(valid_data,\n batch_size=batch_size, \n num_workers=num_workers,\n shuffle=False)\ntest_loader = torch.utils.data.DataLoader(test_data,\n batch_size=batch_size, \n num_workers=num_workers,\n shuffle=False)\nloaders_scratch = {\n 'train': train_loader,\n 'valid': valid_loader,\n 'test': test_loader\n}",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "ee7bd0bd629d0e7fe00be30febcbcce8e3b289a9"
},
"cell_type": "raw",
"source": ""
},
{
"metadata": {
"_uuid": "e5bd76f96291adac574f86f73f516b706a7b2d3a"
},
"cell_type": "markdown",
"source": "**Question 3:** Describe your chosen procedure for preprocessing the data. \n- How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?\n- Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?\n"
},
{
"metadata": {
"_uuid": "20ad44b55c638d9e159a32a24495626909d83a3a"
},
"cell_type": "markdown",
"source": "**Answer**: I've applied RandomResizedCrop & RandomHorizontalFlip to just train_data. This will do both image augmentations and resizing jobs. Image augmentation will give randomness to the dataset so, it prevents overfitting and I can expect better performance of model when it's predicting toward test_data. On the other hand, I've done Resize of (256) and then, center crop to make 224 X 224. Since valid_data will be used for validation check, I will not do image augmentations. For the test_data, I've applied only image resizing."
},
{
"metadata": {
"_uuid": "f40b4caa2ded0cf432c1f54ad0564418edae5d84"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Model Architecture\n\nCreate a CNN to classify dog breed. Use the template in the code cell below."
},
{
"metadata": {
"trusted": true,
"_uuid": "65c25cfabf200708c735b110ae3df1320f3e1d89"
},
"cell_type": "code",
"source": "from PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nnum_classes = 133 # total classes of dog breeds",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "62cd7c8cdd1f827bcb794fba72220e79f72e010d"
},
"cell_type": "code",
"source": "import torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n# define the CNN architecture\nclass Net(nn.Module):\n ### TODO: choose an architecture, and complete the class\n def __init__(self):\n super(Net, self).__init__()\n ## Define layers of a CNN\n self.conv1 = nn.Conv2d(3, 32, 3, stride=2, padding=1)\n self.conv2 = nn.Conv2d(32, 64, 3, stride=2, padding=1)\n self.conv3 = nn.Conv2d(64, 128, 3, padding=1)\n\n # pool\n self.pool = nn.MaxPool2d(2, 2)\n \n # fully-connected\n self.fc1 = nn.Linear(7*7*128, 500)\n self.fc2 = nn.Linear(500, num_classes) \n \n # drop-out\n self.dropout = nn.Dropout(0.3)\n \n def forward(self, x):\n ## Define forward behavior\n x = F.relu(self.conv1(x))\n x = self.pool(x)\n x = F.relu(self.conv2(x))\n x = self.pool(x)\n x = F.relu(self.conv3(x))\n x = self.pool(x)\n \n # flatten\n x = x.view(-1, 7*7*128)\n \n x = self.dropout(x)\n x = F.relu(self.fc1(x))\n \n x = self.dropout(x)\n x = self.fc2(x)\n return x\n\n#-#-# You so NOT have to modify the code below this line. #-#-#\n\n# instantiate the CNN\nmodel_scratch = Net()\nprint(model_scratch)\n\n# move tensors to GPU if CUDA is available\nif use_cuda:\n model_scratch.cuda()",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "5d085a579579af33fbb42299b87e8a1dbd503be2"
},
"cell_type": "markdown",
"source": "__Question 4:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step. "
},
{
"metadata": {
"_uuid": "9b5593847a56fdbbc4abee406387946e78f5f466"
},
"cell_type": "markdown",
"source": "__Answer:__ \n\n(conv1): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n\nactivation: relu\n\n(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n\nactivation: relu\n\n(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n\nactivation: relu\n\n(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n\n(conv3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n\n(dropout): Dropout(p=0.3)\n\n(fc1): Linear(in_features=6272, out_features=500, bias=True)\n\n(dropout): Dropout(p=0.3)\n\n(fc2): Linear(in_features=500, out_features=133, bias=True)\n\nexplanations First 2 conv layers I've applied kernel_size of 3 with stride 2, this will lead to downsize of input image by 2. after 2 conv layers, maxpooling with stride 2 is placed and this will lead to downsize of input image by 2. The 3rd conv layers is consist of kernel_size of 3 with stride 1, and this will not reduce input image. after final maxpooling with stride 2, the total output image size is downsized by factor of 32 and the depth will be 128. I've applied dropout of 0.3 in order to prevent overfitting. Fully-connected layer is placed and then, 2nd fully-connected layer is intended to produce final output_size which predicts classes of breeds."
},
{
"metadata": {
"_uuid": "7533dceb12041fb4226e5201f151444efec2c841"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Specify Loss Function and Optimizer\n\nUse the next code cell to specify a [loss function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [optimizer](http://pytorch.org/docs/stable/optim.html). Save the chosen loss function as `criterion_scratch`, and the optimizer as `optimizer_scratch` below."
},
{
"metadata": {
"trusted": true,
"_uuid": "5a377474a54ca44fd07e41e2f3f1f6fec8d02d7b"
},
"cell_type": "code",
"source": "import torch.optim as optim\n\n### TODO: select loss function\ncriterion_scratch = nn.CrossEntropyLoss()\n\n### TODO: select optimizer\noptimizer_scratch = optim.SGD(model_scratch.parameters(), lr = 0.05)",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "1b4c6edcaaf63a9d1a0d0a7af341ff7244835d86"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Train and Validate the Model\n\nTrain and validate your model in the code cell below. [Save the final model parameters](http://pytorch.org/docs/master/notes/serialization.html) at filepath `'model_scratch.pt'`."
},
{
"metadata": {
"trusted": true,
"_uuid": "1a7c03cf8ff166d6f8b4953dc156e0167db8b3d8"
},
"cell_type": "code",
"source": "def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path, last_validation_loss=None):\n \"\"\"returns trained model\"\"\"\n # initialize tracker for minimum validation loss\n if last_validation_loss is not None:\n valid_loss_min = last_validation_loss\n else:\n valid_loss_min = np.Inf\n \n for epoch in range(1, n_epochs+1):\n # initialize variables to monitor training and validation loss\n train_loss = 0.0\n valid_loss = 0.0\n \n ###################\n # train the model #\n ###################\n model.train()\n for batch_idx, (data, target) in enumerate(loaders['train']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n ## find the loss and update the model parameters accordingly\n ## record the average training loss, using something like\n ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))\n\n # initialize weights to zero\n optimizer.zero_grad()\n \n output = model(data)\n \n # calculate loss\n loss = criterion(output, target)\n \n # back prop\n loss.backward()\n \n # grad\n optimizer.step()\n \n train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))\n \n if batch_idx % 100 == 0:\n print('Epoch %d, Batch %d loss: %.6f' %\n (epoch, batch_idx + 1, train_loss))\n \n ###################### \n # validate the model #\n ######################\n model.eval()\n for batch_idx, (data, target) in enumerate(loaders['valid']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n ## update the average validation loss\n output = model(data)\n loss = criterion(output, target)\n valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))\n\n \n # print training/validation statistics \n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n epoch, \n train_loss,\n valid_loss\n ))\n \n ## TODO: save the model if validation loss has decreased\n if valid_loss < valid_loss_min:\n torch.save(model.state_dict(), save_path)\n print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(\n valid_loss_min,\n valid_loss))\n valid_loss_min = valid_loss\n \n # return trained model\n return model",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "17e4009b197691f0d6fd8a902238698d7a634ff2"
},
"cell_type": "code",
"source": "model_scratch = train(100, loaders_scratch, model_scratch, optimizer_scratch, \n criterion_scratch, use_cuda, 'model_scratch.pt')",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "d80aee11b5a40e485a9f50e9f841cedae2c170c1"
},
"cell_type": "code",
"source": "#load the model that got the best validation accuracy\nmodel_scratch.load_state_dict(torch.load('model_scratch.pt'))",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "dc6ccbcb7a6b2df922f5779d6a865a08dc8eff30"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Test the Model\n\nTry out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%."
},
{
"metadata": {
"trusted": true,
"_uuid": "221d53c0eb0fceb4e231e923f110cca034124386"
},
"cell_type": "code",
"source": "def test(loaders, model, criterion, use_cuda):\n\n # monitor test loss and accuracy\n test_loss = 0.\n correct = 0.\n total = 0.\n\n for batch_idx, (data, target) in enumerate(loaders['test']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the loss\n loss = criterion(output, target)\n # update average test loss \n test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))\n # convert output probabilities to predicted class\n pred = output.data.max(1, keepdim=True)[1]\n # compare predictions to true label\n correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())\n total += data.size(0)\n \n print('Test Loss: {:.6f}\\n'.format(test_loss))\n\n print('\\nTest Accuracy: %2d%% (%2d/%2d)' % (\n 100. * correct / total, correct, total))\n\n# call test function \ntest(loaders_scratch, model_scratch, criterion_scratch, use_cuda)",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "f23579b2c88bb6937f68c94094fdff6ca6f887fd"
},
"cell_type": "markdown",
"source": "---\n<a id='step4'></a>\n## Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)\n\nYou will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.\n\n### (IMPLEMENTATION) Specify Data Loaders for the Dog Dataset\n\nUse the code cell below to write three separate [data loaders](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader) for the training, validation, and test datasets of dog images (located at `dogImages/train`, `dogImages/valid`, and `dogImages/test`, respectively). \n\nIf you like, **you are welcome to use the same data loaders from the previous step**, when you created a CNN from scratch."
},
{
"metadata": {
"trusted": true,
"_uuid": "db6075770e8b9f54b79662649852561eb71a174f"
},
"cell_type": "code",
"source": "## TODO: Specify data loaders\nloaders_transfer = loaders_scratch.copy()",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "16824d748867cf2d6035453cfb61bbb60db5cc71"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Model Architecture\n\nUse transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable `model_transfer`."
},
{
"metadata": {
"trusted": true,
"_uuid": "d470a8ab2ce7e49450255d584962e44d2f656ed8"
},
"cell_type": "code",
"source": "import torchvision.models as models\nimport torch.nn as nn\n\n## TODO: Specify model architecture \nmodel_transfer = models.resnet50(pretrained=True)\n\nfor param in model_transfer.parameters():\n param.requires_grad = False\n\nmodel_transfer.fc = nn.Linear(2048, 133, bias=True)\n\nfc_parameters = model_transfer.fc.parameters()\n\nfor param in fc_parameters:\n param.requires_grad = True\n \nmodel_transfer",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "4ec02181302f57e59a79ca1adedfdb07e8f57d2b"
},
"cell_type": "code",
"source": "if use_cuda:\n model_transfer = model_transfer.cuda()",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "d58c9dd616b3b4a5df7e7cfd8472483d92b6345f"
},
"cell_type": "markdown",
"source": "__Question 5:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem."
},
{
"metadata": {
"_uuid": "a6249291f1bb7b4bee256ffbbfa5a520298b4afd"
},
"cell_type": "markdown",
"source": "__Answer:__ \n\nI picked ResNet as a transfer model because it performed outstanding on Image Classification. I looked into the structure and functions of ResNet. The core idea of ResNet is introducing a so-called “identity shortcut connection” that skips one or more layers. I guess this prevents overfitting when it's training.\n\nI've pull out the final Fully-connected layer and replaced with Fully-connected layer with output of 133 (dog br\n\n\n"
},
{
"metadata": {
"_uuid": "5d1ee45019c95fe313421e00ea455132fee24140"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Specify Loss Function and Optimizer\n\nUse the next code cell to specify a [loss function](http://pytorch.org/docs/master/nn.html#loss-functions) and [optimizer](http://pytorch.org/docs/master/optim.html). Save the chosen loss function as `criterion_transfer`, and the optimizer as `optimizer_transfer` below."
},
{
"metadata": {
"trusted": true,
"_uuid": "e6b7329c5d073826d5c1657cfad5b97d35387818"
},
"cell_type": "code",
"source": "criterion_transfer = nn.CrossEntropyLoss()\noptimizer_transfer = optim.SGD(model_transfer.fc.parameters(), lr=0.001)",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "a3ed40cb5798220854cbfa203f01f6898ba71986"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Train and Validate the Model\n\nTrain and validate your model in the code cell below. [Save the final model parameters](http://pytorch.org/docs/master/notes/serialization.html) at filepath `'model_transfer.pt'`."
},
{
"metadata": {
"trusted": true,
"_uuid": "c281da1bce78441da7f1259e7dbe0ef1ce170f05"
},
"cell_type": "code",
"source": "# train the model\n# train(n_epochs, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')\n\ndef train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):\n \"\"\"returns trained model\"\"\"\n # initialize tracker for minimum validation loss\n valid_loss_min = np.Inf\n \n for epoch in range(1, n_epochs+1):\n # initialize variables to monitor training and validation loss\n train_loss = 0.0\n valid_loss = 0.0\n \n ###################\n # train the model #\n ###################\n model.train()\n for batch_idx, (data, target) in enumerate(loaders['train']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n\n # initialize weights to zero\n optimizer.zero_grad()\n \n output = model(data)\n \n # calculate loss\n loss = criterion(output, target)\n \n # back prop\n loss.backward()\n \n # grad\n optimizer.step()\n \n train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))\n \n if batch_idx % 100 == 0:\n print('Epoch %d, Batch %d loss: %.6f' %\n (epoch, batch_idx + 1, train_loss))\n \n ###################### \n # validate the model #\n ######################\n model.eval()\n for batch_idx, (data, target) in enumerate(loaders['valid']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n ## update the average validation loss\n output = model(data)\n loss = criterion(output, target)\n valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))\n\n \n # print training/validation statistics \n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n epoch, \n train_loss,\n valid_loss\n ))\n \n ## TODO: save the model if validation loss has decreased\n if valid_loss < valid_loss_min:\n torch.save(model.state_dict(), save_path)\n print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(\n valid_loss_min,\n valid_loss))\n valid_loss_min = valid_loss\n \n # return trained model\n return model",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "be41fe0ee9e2527a6416f7c8e801be460fc53ec5"
},
"cell_type": "code",
"source": "train(20, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "76882a685c74ec781c13c1042f89362690e577a6"
},
"cell_type": "code",
"source": "# load the model that got the best validation accuracy\nmodel_transfer.load_state_dict(torch.load('model_transfer.pt'))",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "e908660b9ddbb85cd007f9f6d3a463bd4f0d2f91"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Test the Model\n\nTry out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%."
},
{
"metadata": {
"trusted": true,
"_uuid": "9c994021d9be091847b29af8e4aee748c0ce2a9c"
},
"cell_type": "code",
"source": "test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "57964887de09914988cd290b8f9c9852f9eacc42"
},
"cell_type": "markdown",
"source": "### (IMPLEMENTATION) Predict Dog Breed with the Model\n\nWrite a function that takes an image path as input and returns the dog breed (`Affenpinscher`, `Afghan hound`, etc) that is predicted by your model. "
},
{
"metadata": {
"trusted": true,
"_uuid": "77f67eff2eac7a2b05a893e5ac196acfefc577e8"
},
"cell_type": "code",
"source": "### TODO: Write a function that takes a path to an image as input\n### and returns the dog breed that is predicted by the model.\n\n# list of class names by index, i.e. a name can be accessed like class_names[0]\nclass_names = [item[4:].replace(\"_\", \" \") for item in loaders_transfer['train'].dataset.classes]",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "a87cb2e9579854a5b24964126e1d1a93412ef46b"
},
"cell_type": "code",
"source": "loaders_transfer['train'].dataset.classes[:10]\n",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "0f705ddf9970ade234b51244e114df8ed26c5307"
},
"cell_type": "code",
"source": "class_names[:10]",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "e7570491e46aec94772e8e85c851b03664ba0278"
},
"cell_type": "code",
"source": "from PIL import Image\nimport torchvision.transforms as transforms\n\ndef load_input_image(img_path): \n image = Image.open(img_path).convert('RGB')\n prediction_transform = transforms.Compose([transforms.Resize(size=(224, 224)),\n transforms.ToTensor(), \n standard_normalization])\n\n # discard the transparent, alpha channel (that's the :3) and add the batch dimension\n image = prediction_transform(image)[:3,:,:].unsqueeze(0)\n return image",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "fbdcb97f3c57f74dd0c4d48a1b292a79f0666928"
},
"cell_type": "code",
"source": "def predict_breed_transfer(model, class_names, img_path):\n # load the image and return the predicted breed\n img = load_input_image(img_path)\n model = model.cpu()\n model.eval()\n idx = torch.argmax(model(img))\n return class_names[idx]",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "bac779a410e8c35045aec1676d6d7a71afe2e076"
},
"cell_type": "markdown",
"source": "---\n<a id='step5'></a>\n## Step 5: Write your Algorithm\n\nWrite an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,\n- if a __dog__ is detected in the image, return the predicted breed.\n- if a __human__ is detected in the image, return the resembling dog breed.\n- if __neither__ is detected in the image, provide output that indicates an error.\n\nYou are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the `face_detector` and `human_detector` functions developed above. You are __required__ to use your CNN from Step 4 to predict dog breed. \n\nSome sample output for our algorithm is provided below, but feel free to design your own user experience!\n\n\n\n\n### (IMPLEMENTATION) Write your Algorithm"
},
{
"metadata": {
"trusted": true,
"_uuid": "f507860eed92a08e53784949dfe57a2e5447202c"
},
"cell_type": "code",
"source": "### TODO: Write your algorithm.\n### Feel free to use as many code cells as needed.\n\ndef run_app(img_path):\n ## handle cases for a human face, dog, and neither\n img = Image.open(img_path)\n plt.imshow(img)\n plt.show()\n if dog_detector(img_path) is True:\n prediction = predict_breed_transfer(model_transfer, class_names, img_path)\n print(\"Dogs Detected!\\nIt looks like a {0}\".format(prediction)) \n elif face_detector(img_path) > 0:\n prediction = predict_breed_transfer(model_transfer, class_names, img_path)\n print(\"Hello, human!\\nIf you were a dog..You may look like a {0}\".format(prediction))\n else:\n print(\"Error! Can't detect anything..\")",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"_uuid": "5f991e72e6cbfc5f185140f5174ab90f51975a60"
},
"cell_type": "markdown",
"source": "---\n<a id='step6'></a>\n## Step 6: Test Your Algorithm\n\nIn this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that _you_ look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?\n\n### (IMPLEMENTATION) Test Your Algorithm on Sample Images!\n\nTest your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images. \n\n__Question 6:__ Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm."
},
{
"metadata": {
"_uuid": "3977f80da343a114b00d34d6745b462cc1ca75c4"
},
"cell_type": "markdown",
"source": "__Answer:__ (Three possible points for improvement)\n\nMore image datasets of dogs will improve training models. Also, more image augmentations trials (flipping vertically, move left or right, etc.) will improve performance on test data.\n\nHyper-parameter tunings: weight initializings, learning rates, drop-outs, batch_sizes, and optimizers will be helpful to improve performances.\n\nEnsembles of models"
},
{
"metadata": {
"trusted": true,
"_uuid": "efa628cd6cb299a74d0759aab7677d734b247a6f"
},
"cell_type": "code",
"source": "## TODO: Execute your algorithm from Step 6 on\n## at least 6 images on your computer.\n## Feel free to use as many code cells as needed.\n\n## suggested code, below\nfor file in np.hstack((human_files[:3], dog_files[:3])):\n run_app(file)",
"execution_count": null,
"outputs": []
},
{
"metadata": {
"trusted": true,
"_uuid": "ae9da0b8fe3475e1eca086782624eceb1efedd77"
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.6.6",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
}
},
"nbformat": 4,
"nbformat_minor": 1
}Comments (0)


